import ssl
import random
from paho.mqtt import client as mqtt_client

broker = 'n12ebcd2.ala.cn-hangzhou.emqxsl.cn'
port = 8883
# topic = "message"
topic = "command"
client_id = f'python-mqtt-{random.randint(0, 1000)}'
username = 'emqx'
password = '123456'

# 连接
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
        # 订阅指定的主题
        client.subscribe(topic)
    else:
        print(f"Failed to connect, return code {rc}")

# 打印接收信息
def on_message(client, userdata, msg):
    print(f"Received message: {msg.payload.decode()} on topic {msg.topic}")

def connect_mqtt():
    # 创建客户端实例
    client = mqtt_client.Client(client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    client.on_message = on_message
    # 设置TLS加密
    client.tls_set(certfile=None, keyfile=None, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1_2)
    # 连接到MQTT Broker
    client.connect(broker, port)
    return client

def run():
    # 连接到MQTT broker
    client = connect_mqtt()
    # 启动客户端网络循环
    client.loop_forever()

if __name__ == '__main__':
    run()
